import React, { Component } from 'react';
import { Relax } from 'iflux2';
import noop from 'util/noop';
import { transformURL } from 'util/image';
import { Checkbox } from 'antd';
import Material from 'uikit/material'
import Links from 'uikit/links';
import { fromJS } from 'immutable';

@Relax
export default class AdNewsEdit extends Component {

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            init: true,
            isEditorFull: false
        }
    }

    static defaultProps = {
        tabs: '',
        status: '',
        curItem: {},
        curIndexInItem: 0,
        _changeNewsValue: noop,
        _addNewsValue: noop,
        _changeBatchNewsValue: noop,
        _setEdited: noop
    }

    componentDidUpdate(prevProps) {
        let { curIndexInItem: curIndexInItemPrev } = prevProps;
        let { curItem, curIndexInItem } = this.props;
        //富文本要特殊处理。。。
        if (curIndexInItemPrev !== curIndexInItem) {
            this.um.setContent(curItem.getIn(['content', 'news_item', curIndexInItem, 'content']));
        }
    }

    componentDidMount() {
        const initUMEditor = () => {
            this.um = window.UM.getEditor('editor', {
                UMEDITOR_HOME_URL: '//pic.qianmi.com/ejz/ejz_yun/umeditor/',
                width: 377,
                height: 303,
                toolbars: [
                    ['fullscreen', 'source', 'undo', 'redo', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc']
                ],
            });
            this.um.addListener('contentChange', () => {
                this._setValue('content', this.um.getContent());
            });
            /*重写链接按钮功能*/
            this._clickEventListener('.edui-btn.edui-btn-link', () => {
                this.refs.link.open();
            }, true);
            /*重写图片按钮功能*/
            this._clickEventListener('.edui-btn.edui-btn-image', () => {
                this.refs.image.open('image');
            }, true);
            /*重写全屏按钮功能*/
            this._clickEventListener('.edui-btn.edui-btn-fullscreen', () => {
                this.props.toggleVisible();
            });
        }
        if (window.UM) {
            initUMEditor();
        }
    }

    componentWillUnmount() {
        this.um.destroy && this.um.destroy();
    }

    render() {

        let { status, curItem, curIndexInItem } = this.props;
        //当前正在编辑的  具体哪一条
        const curEditInfo = curItem.getIn(['content', 'news_item', curIndexInItem]) || fromJS({});
        const { title, author, thumb_url, show_cover_pic, digest, content, content_source_url } = curEditInfo.toJS();
        return (
            <div className="editRight">
                <Material ref="image"
                    onSelect={(e) => this.um.execCommand('insertHtml', `<img src="${e.url}" style="width:100%"/>`)} />
                <Links ref="link"
                    onSelect={(e) => this.um.execCommand('link', {
                        url: e.data.url,
                        title: e.data.title,
                        target: '_blank'
                    })} />
                <div className="editPart">
                    <label>标题</label>
                    <br />
                    <input onChange={(event) => {
                        this._setValue('title', event)
                    }} placeholder="请输入标题"
                        type="text" value={title} maxLength={64} />
                </div>
                <div className="editPart">
                    <label>作者<span>（选填）</span></label>
                    <br />
                    <input onChange={(event) => {
                        this._setValue('author', event)
                    }} placeholder="请输入作者"
                        type="text" value={author} maxLength={8} />
                </div>
                <div className="editPart">
                    <label>封面<span>（图片建议尺寸900*500像素）</span></label>
                    <br />
                    {
                        curEditInfo.get('thumb_url')
                            ? <div onClick={() => this.refs.material.open('image', {
                                media_id: curEditInfo.get('thumb_media_id'),
                                url: curEditInfo.get('thumb_url')
                            })} className="pic" style={{ backgroundImage: `url(${transformURL(thumb_url)})` }}/>
                            : <div onClick={() => this.refs.material.open('image')} className="pic fpic"> + </div>
                    }
                    <Material ref="material"
                        onSelect={(e) => this._setBatchValue({ thumb_media_id: e.media_id, thumb_url: e.url })} />
                    <Checkbox checked={show_cover_pic} onChange={(event) => {
                        this._check('show_cover_pic', event)
                    }}>封面图片显示在正文中</Checkbox>
                </div>
                <div className="editPart">
                    <label>摘要</label>
                    <span>（选填，如果不填写会默认抓取正文前54个字）</span>
                    <br />
                    <textarea style={{ wordBreak: "break-all" }} value={digest} cols="30" rows="10" maxLength={120}
                        onChange={(event) => {
                            this._setValue('digest', event)
                        }} resizable={false} />
                </div>
                <div className="editPart">
                    <label>正文</label>
                    <br />
                    <script id="editor" name="content"
                        type="text/plain">{(content || '').replace(/data-src/gm, 'src')}</script>
                </div>
                <div className="editPart" style={{ width: "377px" }}>
                    <Links ref="links" onSelect={(e) => {
                        this._setValue('content_source_url', e.data.url)
                    }} />
                    <div>阅读全文</div>
                    <a className="link" onClick={() => {
                        this.refs.links.open({ type: 'custom', data: { url: content_source_url } })
                    }}>{content_source_url || '设置链接到页面地址'}</a>
                </div>
            </div>
        )
    }

    /*Click事件绑定，未找到元素时会持续绑定事件*/
    _clickEventListener = (exp, callback, remove) => {
        let el = document.querySelector(exp);
        if (el) {
            remove && el.removeEventListener('click');
            el.addEventListener('click', callback);
        } else {
            setTimeout(() => {
                console.warn('event-listener timeout');
                this._clickEventListener(exp, callback, remove);
            }, 1);
        }
    }

    _check = (key, e) => {
        let value = +e.target.checked;
        this._setValue(key, value);
    }

    //修改内容
    _setValue = (key, e) => {
        //分两种，一种传值过来，一种从target里取
        let value = e.target && e.target.value;
        if (!value && value !== '') {
            value = e;
        }
        const { _changeNewsValue, curIndexInItem, _setEdited } = this.props;
        _changeNewsValue({ index: curIndexInItem, key, value });
        if (this.state.init) this.setState({ init: false });
        else _setEdited(true);
    }

    //批量修改内容
    _setBatchValue = (obj) => {
        const { curIndexInItem, _changeBatchNewsValue } = this.props;
        _changeBatchNewsValue({
            index: curIndexInItem,
            obj
        })
    }

}